package com.im.app.processor;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.im.app.model.Code;
import com.im.app.model.Personhost;
import com.im.app.model.VisitorAvatar;
import com.im.app.service.ICodeService;
import com.im.app.service.IPersonhostService;
import com.im.app.service.IUserService;
import com.im.app.service.VisitorAvatarService;
import com.im.app.utils.Constants;

import com.im.app.utils.Https;
import com.im.app.utils.SpringUtils;
import com.im.app.utils.StringUtils;
import org.jim.core.ImChannelContext;
import org.jim.core.http.HttpRequest;
import org.jim.core.packets.LoginReqBody;
import org.jim.core.packets.LoginRespBody;
import org.jim.core.packets.User;
import org.jim.server.JimServerAPI;
import org.jim.server.processor.login.LoginCmdProcessor;
import org.jim.server.protocol.AbstractProtocolCmdProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Component
public class LoginServiceProcessor extends AbstractProtocolCmdProcessor implements LoginCmdProcessor {

    private Logger logger = LoggerFactory.getLogger(LoginServiceProcessor.class);

    private static Map<String,User> cacheUser = new HashMap<>();

    public static LoginServiceProcessor ls;

    @Autowired
    private IUserService userService;

    @Autowired
    private ICodeService codeService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private IPersonhostService personhostService;

    @Autowired
    private VisitorAvatarService visitorAvatarService;

    @PostConstruct
    public void init() {
        ls = this;
        ls.userService = this.userService;
        ls.codeService = this.codeService;
        ls.request=this.request;
        ls.personhostService=this.personhostService;
        ls.visitorAvatarService=this.visitorAvatarService;
    }



    @Override
    public LoginRespBody doLogin(LoginReqBody loginReqBody, ImChannelContext imChannelContext) {

        if(loginReqBody.getType() == 1){
            return doServerLogin(loginReqBody,imChannelContext);
        } else if (loginReqBody.getType() == 2) {
            return doClientLogin(loginReqBody,imChannelContext);
        }

        return LoginRespBody.failed("登录类型有误");


//        String userId = loginReqBody.getUserId();
//        List<ImChannelContext> byUserId = JimServerAPI.getByUserId(userId);
//
//
//        return LoginRespBody.success();
    }

    //客服登录
    @Override
    public LoginRespBody doServerLogin(LoginReqBody loginReqBody, ImChannelContext imChannelContext) {
        String password = loginReqBody.getPassword();
        if(StringUtils.isEmpty(password)){
            return LoginRespBody.failed("登陆卡密不能为空");
        }
        QueryWrapper<Code> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("kamicode",password);
        Code code = ls.codeService.getOne(queryWrapper);
        if(code == null){
            return LoginRespBody.failed("卡密有误");
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("kamicode",password);
        userQueryWrapper.select("user_id,name,face_url,status,on_line,terminal,act_status,end_time");
        User user=ls.userService.getOne(userQueryWrapper);
        if(null==user) {
            return LoginRespBody.failed("卡密有误");
        }
        if(Constants.KAMINOUSE.equals(code.getKamistatus())){ //未激活 需要去激活用户
                Calendar rightNow = Calendar.getInstance();
                if(Constants.USECESHI.equals(code.getKamitype())){
                    rightNow.add(Calendar.HOUR,2);
                }else if(Constants.USELOGIN.equals(code.getKamitype())){
                    rightNow.add(Calendar.DATE,code.getDays());
                }
                user.setActStatus(1);
                user.setEndTime(rightNow.getTime());
                boolean updateById =ls.userService.updateById(user);
                if(updateById){
                    code.setKamistatus(Constants.KAMIINUSE);
                    code.setUsetime(new Date());
                    ls.codeService.updateById(code);
                }
        }
        if(new Date().getTime()>user.getEndTime().getTime()) {
            return LoginRespBody.failed("账号已到期");
        }

        if (user.getStatus()==0){
            return LoginRespBody.failed("账号被冻结");
        }
        String ip= imChannelContext.getSessionContext().getImClientNode().getIp();

        user.setIp(ip);
        ls.userService.updateById(user);
        LoginRespBody respBody = LoginRespBody.success();
//        cacheUser.put(user.getUserId(),user);
        respBody.setUser(user);
        return respBody;
    }

    //用户登录
    @Override
    public LoginRespBody doClientLogin(LoginReqBody loginReqBody, ImChannelContext imChannelContext) {
        QueryWrapper<Personhost> personhostQueryWrapper = new QueryWrapper<>();
        personhostQueryWrapper.eq("shortcode",loginReqBody);
        Personhost personhost=ls.personhostService.getOne(personhostQueryWrapper);
        if (personhost == null){
            return LoginRespBody.failed("code不合法");
        }
        String ip= imChannelContext.getSessionContext().getImClientNode().getIp();
        String kefuid= personhost.getUserId(); //通过code获得userId
        QueryWrapper<User> queryWrapper=new QueryWrapper<User>();
        queryWrapper.eq("user_id",loginReqBody.getUserId());
        User user=ls.userService.getOne(queryWrapper);
        if(null==user){
            user=ls.userService.getUserByKefuIdAndIp(kefuid,ip);
        }
        if(user != null){ //用户有缓存 并登入过
            if(user.getStatus()==2){
                return LoginRespBody.failed("用户在黑名单");
            }
            LoginRespBody respBody = LoginRespBody.success();
            respBody.setUser(user);
            return respBody;
        }else { //新注册 本地缓存 和 数据都没有
            VisitorAvatar visitorAvatar =ls.visitorAvatarService.getVisitorAvatarByRandom();
            if (visitorAvatar == null){
                return LoginRespBody.failed("系统出错");
            }
            String nickname= visitorAvatar.getName();
            String userId =  loginReqBody.getUserId();
            String avatar = visitorAvatar.getAvatar();
            User user1=new User();
            user1.setUserId(userId);
            user1.setIp(ip);
            user1.setAvatar(avatar);
            user1.setName(nickname);
            user1.setKefuId(kefuid);
            user1.setAppMangerLevel(1);
            ls.userService.save(user1);
            LoginRespBody respBody = LoginRespBody.success();
            respBody.setUser(user1);
            return respBody;
        }

    }



    @Override
    public User getUser(LoginReqBody loginReqBody, ImChannelContext imChannelContext) {

//        List<ImChannelContext> byUserId = JimServerAPI.getByUserId("");

        String code = loginReqBody.getUserId();
        User user = cacheUser.get(code);
        if(user != null){
            return user;
        }
        return null;
//        user = new User();
//        user.setUserId(code);
//        user.setName("梦之蓝");
//        user.setStatus(1);
//        user.setAvatar("https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKS86nGzsQT6bVciaSGNNckGuDvxpjSXkQwTibt736d6JeCubxF5n57bopia6QvfuicThUShcLMOia73iag/132");
//        return user;
    }


    @Override
    public void onSuccess(User user, ImChannelContext imChannelContext){




        logger.info("登录成功回调方法");

    }

    @Override
    public void onFailed(ImChannelContext imChannelContext) {
        logger.info("登录失败回调方法");
    }

    private String createNum(){

        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb = new StringBuilder(4);
        for(int i=0;i<4;i++) {
            char ch=str.charAt(new Random().nextInt(str.length()));
            sb.append(ch);
        }
        return sb.toString();
    }
}
